'use strict';
import Base from './base.js';
const jwt = require('jsonwebtoken');
const WXBizDataCrypt = require('./WXBizDataCrypt');
// 美易通系统类控制器请求方法
module.exports = class extends Base {
  // 微信用户快速登录
  async getphoneNumberAction() {
    const orcode = this.post('orcode');
    const iv = this.post('iv');
    const code = this.post('code');
    const encryptedData = this.post('encryptedData');
    const sessionData = await this.fetch('https://api.weixin.qq.com/sns/jscode2session?appid=' + think.config('mytmini.appid') + '&secret=' + think.config('mytmini.secret') + '&js_code=' + code + '&grant_type=authorization_code').then(res => res.json());
    // 是否返回openid
    if (think.isEmpty(sessionData.openid)) {
      return this.fail('登录失败');
    }
    // 获取用户手机号
    var appId = think.config('mytmini.appid');
    var pc = new WXBizDataCrypt(appId, sessionData.session_key);
    var phoneData = await pc.decryptData(encryptedData, iv);
    const username = phoneData.phoneNumber;
    const openid = sessionData.openid;
    // 判断此openid是否绑定过
    const info = await this.model().query(`SELECT au.id,au.name,au.sex,od.orcode,org.jsonshop,org.modelarr,od.floor,au.departmentid,od.name as departmentname,au.ismanage,au.isdisable FROM think_or_app_user au LEFT JOIN think_or_department od ON au.departmentid = od.id LEFT JOIN think_or_rulegroup org ON au.zhichengid = org.groupid WHERE od.orcode = ${orcode} AND au.username =${username}`);
    // 生成token
    const token = jwt.sign(sessionData, think.config('mytmini.jwtSecret'), { expiresIn: '7d' });
    // 根据openid查找用户是否已经注册
    const resinfo = await this.model('or_app_user').where(`xcx_openid = "${openid}" AND username = ${username}`).field('id,xcx_openid').find();
    if (think.isEmpty(info)) {
      return this.json({ 'code': '0', 'msg': '连锁编号或账号或密码不正确...', 'data': info, token: token, phoneData });
    } else {
      if (info[0].isdisable == 1) {
        return this.json({ 'code': '0', 'msg': '离职员工不可登陆...', 'data': info, token: token, phoneData });
      } else {
        if (think.isEmpty(info[0].modelarr)) {
          info[0].modelarr = 0;
        }
        return this.json({ 'code': '200', 'msg': '登录成功...', 'data': info, token: token, phoneData });
      }
    }
  }
  // 请求登录
  async getloginAction() {
    const code = this.post('code');
    const orcode = this.post('orcode');
    const username = this.post('username');
    const password = think.md5(this.post('password'));
    const sessionData = await this.fetch('https://api.weixin.qq.com/sns/jscode2session?appid=' + think.config('mytmini.appid') + '&secret=' + think.config('mytmini.secret') + '&js_code=' + code + '&grant_type=authorization_code').then(res => res.json());
    const info = await this.model().query(' SELECT au.id,au.name,au.sex,od.orcode,org.jsonshop,org.modelarr,od.floor,au.departmentid,od.name as departmentname,au.ismanage,au.isdisable FROM `think_or_app_user` au LEFT JOIN `think_or_department` od ON au.departmentid = od.id LEFT JOIN `think_or_rulegroup` org ON au.zhichengid = org.groupid WHERE od.orcode = ' + orcode + ' AND au.username = "' + username + '" AND au.password = "' + password + '" ');
    // 生成token
    const token = jwt.sign(sessionData, think.config('mytmini.jwtSecret'), { expiresIn: '7d' });
    if (think.isEmpty(info)) {
      return this.json({ 'code': '200', 'msg': '连锁编号或账号或密码不正确...', 'data': info });
    } else {
      if (info[0].isdisable == 1) {
        return this.json({ 'code': '200', 'msg': '离职员工不可登陆...', 'data': info, token: token });
      } else {
        if (think.isEmpty(info[0].modelarr)) {
          info[0].modelarr = 0;
        }
        return this.json({ 'code': '100', 'msg': '登录成功...', 'data': info, token: token });
      }
    }
  }
  // 更改密码
  async changepassAction() {
    const that = this;
    const data = that.post();
    const id = data.userid;
    const oldpass = think.md5(data.oldpass);
    const newpass = think.md5(data.newpass);
    const password = await that.model('or_app_user').where({ id: id }).getField('password');
    if (password[0] !== oldpass) {
      return that.json({ code: '100', msg: '原密码不正确' });
    }
    const affectedRows = await that.model('or_app_user').where({ id: id }).update({ password: newpass });
    return affectedRows ? that.json({ code: '200', msg: '密码更改成功' }) : that.json({ code: '100', msg: '密码更改失败' });
  }
  // 获取七牛上传图片的验证token
  async gettokenAction() {
    const qiniu = require('qiniu');
    // 需要填写你的 Access Key 和 Secret Key
    qiniu.conf.ACCESS_KEY = this.config('qiniu.ACCESS_KEY');
    qiniu.conf.SECRET_KEY = this.config('qiniu.SECRET_KEY');
    // 要上传的空间
    const bucket = this.config('qiniu.BUCKET');

    const mac = new qiniu.auth.digest.Mac(qiniu.conf.ACCESS_KEY, qiniu.conf.SECRET_KEY);
    const putPolicy = new qiniu.rs.PutPolicy({
      scope: bucket
    });
    const uploadToken = putPolicy.uploadToken(mac);

    const data = {'uptoken': uploadToken};
    return this.json(data);
  }
  // 请求获取系统机构信息
  async getsyorcodesysteminfoAction() {
    const orcode = this.get('orcode');
    // 机构名称
    const info = await this.model().query(' SELECT name,orcode FROM `think_or_department` WHERE orcode = ' + orcode + ' AND floor = 0 ');
    // 机构下分店数量
    const shopnum = await this.model().query(' SELECT IFNULL(count(id),0) as shopnum FROM `think_or_department` WHERE orcode = ' + orcode + ' AND floor = 1 ');
    // 机构下所有员工的数量
    const workernum = await this.model().query(' SELECT IFNULL(count(au.id),0) as workernum FROM `think_or_app_user` au LEFT JOIN `think_or_department` od ON au.departmentid = od.id WHERE od.orcode = ' + orcode + ' ');
    // 机构下客户数量
    const guestnum = await this.model().query(' SELECT IFNULL(count(og.id),0) as guestnum FROM `think_or_guest` og LEFT JOIN `think_or_department` od ON og.departmentid = od.id WHERE od.orcode = ' + orcode + ' ');
    // 机构下订单数量
    const ordernum = await this.model().query(' SELECT IFNULL(count(oso.id),0) as ordernum FROM `think_or_shop_order` oso LEFT JOIN `think_or_department` od ON oso.departmentid = od.id WHERE od.orcode = ' + orcode + ' ');
    // 机构下的订单总金额
    const amount = await this.model().query(' SELECT IFNULL(sum(oso.recemoney),0) as amount FROM `think_or_shop_order` oso LEFT JOIN `think_or_department` od ON oso.departmentid = od.id WHERE od.orcode = ' + orcode + ' AND oso.status <> 0 ');
    // 机构的系统开通时间和结束时间
    const time = await this.model().query(' SELECT odi.begintime,odi.endtime FROM `think_or_department` od LEFT JOIN `think_or_department_info` odi ON od.id = odi.departmentid WHERE od.orcode = ' + orcode + ' AND od.floor = 0 ');

    return think.isEmpty(info) ? this.json({ 'code': '200', 'msg': '没有数据...', 'data': '' }) : this.json({ 'code': '100', 'msg': '查询成功...', 'base': info, 'shopnum': shopnum, 'workernum': workernum, 'guestnum': guestnum, 'ordernum': ordernum, 'amount': amount, 'time': time });
  }
  // 请求获取机构人员管理店的数量及信息
  async getmyjsonshoplistAction() {
    const jsonshop = this.get('jsonshop');
    const info = await this.model().query(' SELECT id,name FROM `think_or_department` WHERE id in (' + jsonshop + ') ');
    return think.isEmpty(info) ? this.json({ 'code': '200', 'msg': '请设置你的管理权限！', 'data': '' }) : this.json({ 'code': '100', 'msg': '查找成功...', 'data': info });
  }
  // 请求获取首页动态的图表数据
  async getsystemdongtaiAction() {
    const orcode = this.post('orcode');
    const jsonshop = this.post('jsonshop');
    const floor = this.post('floor');
    const ismanage = this.post('ismanage');
    const user_id = this.post('user_id');
    // 获取本月开始的时间戳
    var starttime = Math.round(new Date(new Date().getFullYear(), new Date().getMonth(), 1).getTime() / 1000);
    // 本月结束时间
    var endtime = Math.round(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1).getTime() / 1000);
    switch (floor) {
      // 如果是总部运营和店长
      case 0:
      case 1:
        var chartsinfo = await this.model().query('SELECT IFNULL(sum(xianjinyeji),0) as xianjinyeji,IFNULL(sum(kahaoyeji),0) as kahaoyeji,day(FROM_UNIXTIME(addtime)) as day FROM `think_or_shop_yejiticheng` WHERE addtime >= ' + starttime + ' AND addtime < ' + endtime + ' AND shopid IN (' + jsonshop + ') GROUP BY day ');
        break;
      // 如果是经理
      case 2:
        var chartsinfo = await this.model().query('SELECT IFNULL(sum(xianjinyeji),0) as xianjinyeji,IFNULL(sum(kahaoyeji),0) as kahaoyeji,day(FROM_UNIXTIME(addtime)) as day FROM `think_or_shop_yejiticheng` WHERE addtime >= ' + starttime + ' AND addtime < ' + endtime + ' AND bumenid = ' + jsonshop + ' GROUP BY day ');
        break;
      // 如果是小组
      case 3:
        if (ismanage == 1) { // 如果是管理层
          var chartsinfo = await this.model().query('SELECT IFNULL(sum(xianjinyeji),0) as xianjinyeji,IFNULL(sum(kahaoyeji),0) as kahaoyeji,day(FROM_UNIXTIME(addtime)) as day FROM `think_or_shop_yejiticheng` WHERE addtime >= ' + starttime + ' AND addtime < ' + endtime + ' AND xiaozuid = ' + jsonshop + ' GROUP BY day ');
        } else { // 如果是普通员工
          var chartsinfo = await this.model().query('SELECT IFNULL(sum(xianjinyeji),0) as xianjinyeji,IFNULL(sum(kahaoyeji),0) as kahaoyeji,day(FROM_UNIXTIME(addtime)) as day FROM `think_or_shop_yejiticheng` WHERE addtime >= ' + starttime + ' AND addtime < ' + endtime + ' AND userid = ' + user_id + ' GROUP BY day ');
        }
        break;
    }

    return this.json({ 'code': '100', 'msg': '查找成功...', 'data': chartsinfo });
  }
  // 请求获取首页动态展示数据
  async getindexdongtaiAction() {
    const user_id = this.get('user_id');
    const jsonshop = this.get('jsonshop');
    const floor = this.get('floor');
    const ismanage = this.get('ismanage');
    const departmentid = this.get('departmentid');
    const datatype = this.get('datatype');
    // console.log('_______________________'+datatype+' ');
    // post
    const starttime = Math.round(new Date(new Date().toDateString()).getTime() / 1000);
    // 今天结束时间
    const endtime = starttime + 86400;
    // 定义api获取地址
    const datapath = think.config('mypath');
    const getapi = this.controller(datapath + '/database');
    if (floor == 3 && ismanage == 0) { // 如果是普通员工
      const basenum = await getapi.getguestplannum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 规划客数
      const comenum = await getapi.getguestcomenum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 到店客数
      const bespeaknum = await getapi.getguestbesknum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 预约客户数量
      const bespeakarrive = await getapi.getguestbeskarrivenum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 预约到店数量
      const planfeat = await getapi.getyejiplanxianjin(starttime, endtime, floor, jsonshop, ismanage, user_id);// 规划现金业绩
      const xianjin = await getapi.getyejixianjin(starttime, endtime, floor, jsonshop, ismanage, user_id);// 实际现金业绩
      const kahao = await getapi.getyejikahao(starttime, endtime, floor, jsonshop, ismanage, user_id);// 卡耗业绩

      return this.json({ 'data': { 'basenum': basenum, 'comenum': comenum, 'bespeaknum': bespeaknum, 'bespeakarrive': bespeakarrive, 'planfeat': planfeat, 'xianjin': xianjin, 'kahao': kahao } });
    } else { // 如果不是普通员工
      const allworknum = await getapi.getworkermanagenum(floor, jsonshop, ismanage, departmentid, datatype);// 管理员工总数
      const worknum = await getapi.getworkerworkonnum(starttime, endtime, floor, jsonshop, ismanage, departmentid, datatype);// 出勤员工数量
      const ablenum = await getapi.getworkersalenum(starttime, endtime, floor, jsonshop, ismanage, departmentid, datatype);// 出单员工数量
      const basenum = await getapi.getguestplannum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 规划客数
      const comenum = await getapi.getguestcomenum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 到店客数
      const bespeaknum = await getapi.getguestbesknum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 预约客户数量
      const bespeakarrive = await getapi.getguestbeskarrivenum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 预约到店数量
      const planfeat = await getapi.getyejiplanxianjin(starttime, endtime, floor, jsonshop, ismanage, user_id);// 规划现金业绩
      const xianjin = await getapi.getyejixianjin(starttime, endtime, floor, jsonshop, ismanage, user_id);// 实际现金业绩
      const kahao = await getapi.getyejikahao(starttime, endtime, floor, jsonshop, ismanage, user_id);// 卡耗业绩

      return this.json({ 'data': { 'allworknum': allworknum, 'worknum': worknum, 'ablenum': ablenum, 'basenum': basenum, 'comenum': comenum, 'bespeaknum': bespeaknum, 'bespeakarrive': bespeakarrive, 'planfeat': planfeat, 'xianjin': xianjin, 'kahao': kahao } });
    }
  }
  // 请求获取机构的订单捷报列表
  async getorcodeorderlistAction() {
    const orcode = this.get('orcode');
    const page = this.get('page');
    const size = this.get('size');
    const nowpage = page * size;
    const res = await this.model().query('SELECT osy.userid,au.name,au.sex,au.headurl,od.name as shopname,IFNULL(osy.xianjinyeji,0) as xianjinyeji,osy.addtime,IFNULL(osy.kahaoyeji,0) as kahaoyeji FROM `think_or_shop_yejiticheng` osy LEFT JOIN `think_or_app_user` au ON osy.userid = au.id LEFT JOIN `think_or_department` od ON au.shopid = od.id WHERE od.orcode = ' + orcode + ' ORDER BY osy.addtime DESC LIMIT ' + nowpage + ',' + size + ' ');
    for (var i = 0; i < res.length; i++) {
      const starttime = Math.round(new Date(new Date(res[i].addtime * 1000).toDateString()).getTime() / 1000);
      const num = await this.model().query('SELECT COUNT(id) as num FROM `think_or_shop_yejiticheng` WHERE addtime >= ' + starttime + ' AND addtime < ' + res[i].addtime + ' AND userid = ' + res[i].userid + ' ');
      res[i].ordernum = num[0].num + 1;
    }

    return think.isEmpty(res) ? this.json({ 'code': '200', 'msg': '查找失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': '查询成功...', 'orderlist': res });
  }
  // 请求工作页面top信息记录数量
  async getsystemworkinfoAction() {
    const jsonshop = this.get('jsonshop');
    const floor = this.get('floor');
    const ismanage = this.get('ismanage');
    const user_id = this.get('user_id');
    // 定义api获取地址
    const datapath = think.config('mypath');
    const getapi = this.controller(datapath + '/database');
    // 30天前的当天开始时间
    const starttime_30 = Math.round(new Date(new Date().toDateString()).getTime() / 1000) - 86400 * 7;
    const nowtime = Math.round(Date.now() / 1000);
    // 当前年、月、日
    const year = new Date().getFullYear(); // 获取年份
    const month = new Date().getMonth() + 1; // 获取月份
    const day = new Date().getDate(); // 获取日期
    // 获取今日开始的时间戳
    const starttime = Math.round(new Date(new Date().toDateString()).getTime() / 1000);
    // 今天结束时间
    const endtime = starttime + 86400;

    const fuwunum = await getapi.getworkfuwunum(starttime_30, nowtime, floor, jsonshop, ismanage, user_id);// 未完成的服务记录
    const huifangnum = await getapi.getworkhuifangnum(starttime_30, nowtime, floor, jsonshop, ismanage, user_id);// 未完成的服务记录
    const daynum = await getapi.getworkermynomanageday(year, month, day, user_id);// 我的未完成的日程数量
    const sheettype = await getapi.getworkertodayisdaysheet(starttime, endtime, user_id);// 我今日的报表情况
    return this.json({ 'code': '100', 'msg': '查找成功...', 'fuwunum': fuwunum, 'huifangnum': huifangnum, 'daynum': daynum, 'sheettype': sheettype });
  }
  // 请求获取app上的所有权限列表
  async getappallauthorityAction() {
    const res = await this.model().query('SELECT * FROM `think_or_rulemodel` WHERE category = 1 or category = 2 ');
    return think.isEmpty(res) ? this.json({ 'code': '200', 'msg': '没有数据...', 'data': '' }) : this.json({ 'code': '100', 'msg': '查询成功...', 'data': res });
  }
  // 请求刷新用户权限
  async getuserauthorityAction() {
    const user_id = this.get('user_id');
    const authority = await this.model().query('SELECT org.modelarr FROM `think_or_app_user` au LEFT JOIN `think_or_rulegroup` org ON au.zhichengid = org.groupid WHERE au.id = ' + user_id + '  ');
    return think.isEmpty(authority) ? this.json({ 'code': '200', 'msg': '没有数据...', 'data': '' }) : this.json({ 'code': '100', 'msg': '查询成功...', 'data': authority });
  }
  // 请求提交并修改密码
  async postchangepwdAction() {
    const user_id = this.post('user_id');
    const nowpassword = think.md5(this.post('nowpassword'));
    const password = think.md5(this.post('password'));
    const info = await this.model().query('SELECT password FROM `think_or_app_user` WHERE id = ' + user_id + ' ');
    // console.log(password)
    if (info[0].password == nowpassword) {
      const res = await this.model('or_app_user').where({ id: user_id }).update({ password: password });
      return think.isEmpty(res) ? this.json({ 'code': '200', 'msg': '修改失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': '修改成功...', 'data': '' });
    } else {
      return this.json({ 'code': '200', 'msg': '现在的密码不正确！...', 'data': '' });
    }
  }
  // 请求用户提交设置出勤状态
  async postonworkAction() {
    const user_id = this.post('user_id');
    const type = this.post('type');
    const latitude = this.post('latitude');
    const longitude = this.post('longitude');
    const time_start = Math.round(Date.now() / 1000);
    const address = this.post('address');
    const data = {};
    data['userid'] = user_id;
    data['type'] = type;
    data['time_start'] = time_start;
    data['latitude'] = latitude;
    data['longitude'] = longitude;
    data['address'] = address;
    // 获取今日开始的时间戳
    const starttime = Math.round(new Date(new Date().toDateString()).getTime() / 1000);
    // 今天结束时间
    const endtime = starttime + 86400;
    // 查找今天是否已经提交了考勤
    const info = await this.model().query(' SELECT id FROM `think_or_user_work` WHERE userid = ' + user_id + ' AND time_start >= ' + starttime + ' AND time_start < ' + endtime + ' ');
    if (think.isEmpty(info)) {
      // 提交数据到数据库
      const res = await this.model('or_user_work').add(data);
      // 返回结果数据
      return think.isEmpty(res) ? this.json({ 'code': '200', 'msg': '执行失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': 'success...', 'data': res });
    } else {
      return this.json({ 'code': '200', 'msg': '不要重复出勤...', 'data': '' });
    }
  }
  // 请求用户结束出勤状态
  async postendworkAction() {
    const id = this.post('id');
    const type = this.post('type');
    const time_end = Math.round(Date.now() / 1000);
    const latitude = this.post('latitude');
    const longitude = this.post('longitude');
    const address = this.post('address');
    const data = {};
    data['type'] = type;
    data['time_end'] = time_end;
    data['latitude'] = latitude;
    data['longitude'] = longitude;
    data['address'] = address;
    // 提交数据到数据库
    const res = await this.model('or_user_work').where({ id: id }).update(data);
    // 返回结果数据
    return think.isEmpty(res) ? this.json({ 'code': '200', 'msg': '执行失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': 'success...', 'data': res });
  }
  // 请求获取店内产品列表
  async getshopgoodslistAction() {
    const user_id = this.get('user_id');
    // 获取该店的id
    const shopid = await this.model('or_app_user').where({ id: user_id }).field('shopid').find();
    const res = await this.model().query(' SELECT ob.id as brandid,ob.name as brandname,og.name as goodsname,osg.id as goodsid,osg.price FROM `think_or_shop_goods` osg LEFT JOIN `think_or_goods` og ON osg.goodsid = og.id LEFT JOIN `think_or_brand` ob ON og.brandid = ob.id WHERE osg.shopid = ' + shopid.shopid + ' ');

    return think.isEmpty(res) ? this.json({ 'code': '200', 'msg': '执行失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': 'success...', 'data': res });
  }
  // 请求获取店内项目列表
  async getshopsubjectlistAction() {
    const user_id = this.get('user_id');
    // 获取该店的id
    const shopid = await this.model('or_app_user').where({ id: user_id }).field('shopid').find();
    const res = await this.model().query('SELECT osc.id as brandid,osc.name as brandname,os.name as goodsname,oss.id as goodsid,oss.price FROM `think_or_shop_subject` oss LEFT JOIN `think_or_subject` os ON oss.subjectid = os.id LEFT JOIN `think_or_subjectcategory` osc ON os.categoryid = osc.id  WHERE oss.shopid = ' + shopid.shopid + ' ');
    return think.isEmpty(res) ? this.json({ 'code': '200', 'msg': '执行失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': 'success...', 'data': res });
  }
  // 获取机构里的会员诊断设置信息
  async getadmindiagnosedlistAction() {
    const orcode = this.get('orcode');
    const guest_id = this.get('guest_id');
    const type = this.get('type');
    const info = await this.model().query(' SELECT odsc.id as topid,odsc.name as topname,ods.id as listid,ods.name as listname,odsc.id FROM `think_or_diagnosis` ods LEFT JOIN `think_or_diagnosiscategory` odsc ON ods.categoryid = odsc.id WHERE odsc.orcode = ' + orcode + ' AND odsc.pid = ' + type + ' ');
    const info1 = await this.model().query(' SELECT categoryid,status FROM `think_or_shop_guest_zengduan` WHERE guestid = ' + guest_id + ' ');
    return think.isEmpty(info) ? this.json({ 'code': '200', 'msg': '点赞失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': '点赞成功+1...', 'data': info, 'selected': info1 });
  }
  // 设置会员诊断信息
  async postguestzengduanAction() {
    const guest_id = this.post('guest_id');
    const categoryid = this.post('categoryid');
    const info = await this.model().query('SELECT id,status FROM `think_or_shop_guest_zengduan` WHERE categoryid = ' + categoryid + ' AND guestid = ' + guest_id + ' ');

    if (think.isEmpty(info)) {
      const info1 = await this.model('or_shop_guest_zengduan').add({ guestid: guest_id, categoryid: categoryid, status: 1 });
      return think.isEmpty(info1) ? this.json({ 'code': '200', 'msg': '修改失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': '修改成功...', 'data': 1 });
    } else {
      if (info[0].status == 1) {
        const info1 = await this.model('or_shop_guest_zengduan').where({ id: info[0].id }).update({ status: 0 });
        return think.isEmpty(info1) ? this.json({ 'code': '200', 'msg': '修改失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': '修改成功...', 'data': 2 });
      } else {
        const info1 = await this.model('or_shop_guest_zengduan').where({ id: info[0].id }).update({ status: 1 });
        return think.isEmpty(info1) ? this.json({ 'code': '200', 'msg': '修改失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': '修改成功...', 'data': 3 });
      }
    }
  }
  // 获取为完成的服务记录
  async getordernojilutodaylistAction() {
    const floor = this.get('floor');
    const jsonshop = this.get('jsonshop');
    const ismanage = this.get('ismanage');
    const user_id = this.get('user_id');
    // 30天前的当天开始时间
    const starttime = Math.round(new Date(new Date().toDateString()).getTime() / 1000) - 86400 * 7;
    const endtime = Math.round(Date.now() / 1000);
    switch (floor) {
      case '0':
      case '1':
        var info = await this.model().query('SELECT au.name as username,og.name as guestname,au.headurl,osy.fuwujilu,osy.addtime,au.sex,og.sex as gsex,osy.id FROM `think_or_shop_yejiticheng` osy LEFT JOIN `think_or_app_user` au ON osy.userid = au.id LEFT JOIN `think_or_guest` og ON osy.guestid = og.id WHERE osy.addtime >= ' + starttime + ' AND osy.addtime < ' + endtime + ' AND au.shopid IN (' + jsonshop + ') AND osy.fuwujilu = 0 AND osy.guestid <> 0 AND osy.guestid <> 1');
        break;
      case '2':
        var info = await this.model().query('SELECT au.name as username,og.name as guestname,au.headurl,osy.fuwujilu,osy.addtime,au.sex,og.sex as gsex,osy.id FROM `think_or_shop_yejiticheng` osy LEFT JOIN `think_or_app_user` au ON osy.userid = au.id LEFT JOIN `think_or_guest` og ON osy.guestid = og.id WHERE osy.addtime >= ' + starttime + ' AND osy.addtime < ' + endtime + ' AND au.bumenid = ' + jsonshop + ' AND osy.fuwujilu = 0 AND osy.guestid <> 0 AND osy.guestid <> 1 ');
        break;
      case '3':
        if (ismanage == 1) {
          var info = await this.model().query('SELECT au.name as username,og.name as guestname,au.headurl,osy.fuwujilu,osy.addtime,au.sex,og.sex as gsex,osy.id FROM `think_or_shop_yejiticheng` osy LEFT JOIN `think_or_app_user` au ON osy.userid = au.id LEFT JOIN `think_or_guest` og ON osy.guestid = og.id WHERE osy.addtime >= ' + starttime + ' AND osy.addtime < ' + endtime + ' AND au.xiaozuid = ' + jsonshop + ' AND osy.fuwujilu = 0 AND osy.guestid <> 0 AND osy.guestid <> 1 ');
        } else {
          var info = await this.model().query('SELECT au.name as username,og.name as guestname,au.headurl,osy.fuwujilu,osy.addtime,au.sex,og.sex as gsex,osy.id FROM `think_or_shop_yejiticheng` osy LEFT JOIN `think_or_app_user` au ON osy.userid = au.id LEFT JOIN `think_or_guest` og ON osy.guestid = og.id WHERE osy.addtime >= ' + starttime + ' AND osy.addtime < ' + endtime + ' AND au.id = ' + user_id + ' AND osy.fuwujilu = 0 AND osy.guestid <> 0 AND osy.guestid <> 1  ');
        }
        break;
    }

    return think.isEmpty(info) ? this.json({ 'code': '200', 'msg': '查找失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': '查找成功...', 'data': info });
  }
  // 获取为完成的回访记录
  async getordernohuifangtodaylistAction() {
    const floor = this.get('floor');
    const jsonshop = this.get('jsonshop');
    const ismanage = this.get('ismanage');
    const user_id = this.get('user_id');
    // 30天前的当天开始时间
    const starttime = Math.round(new Date(new Date().toDateString()).getTime() / 1000) - 86400 * 7;
    const endtime = Math.round(Date.now() / 1000);
    switch (floor) {
      case '0':
      case '1':
        var info = await this.model().query('SELECT au.name as username,og.name as guestname,au.headurl,osy.huifangjilu,osy.addtime,au.sex,og.sex as gsex,osy.id FROM `think_or_shop_yejiticheng` osy LEFT JOIN `think_or_app_user` au ON osy.userid = au.id LEFT JOIN `think_or_guest` og ON osy.guestid = og.id WHERE osy.addtime >= ' + starttime + ' AND osy.addtime < ' + endtime + ' AND au.shopid IN (' + jsonshop + ') AND osy.huifangjilu = 0 AND osy.guestid <> 0 AND osy.guestid <> 1');
        break;
      case '2':
        var info = await this.model().query('SELECT au.name as username,og.name as guestname,au.headurl,osy.huifangjilu,osy.addtime,au.sex,og.sex as gsex,osy.id FROM `think_or_shop_yejiticheng` osy LEFT JOIN `think_or_app_user` au ON osy.userid = au.id LEFT JOIN `think_or_guest` og ON osy.guestid = og.id WHERE osy.addtime >= ' + starttime + ' AND osy.addtime < ' + endtime + ' AND au.bumenid = ' + jsonshop + ' AND osy.huifangjilu = 0 AND osy.guestid <> 0 AND osy.guestid <> 1 ');
        break;
      case '3':
        if (ismanage == 1) {
          var info = await this.model().query('SELECT au.name as username,og.name as guestname,au.headurl,osy.huifangjilu,osy.addtime,au.sex,og.sex as gsex,osy.id FROM `think_or_shop_yejiticheng` osy LEFT JOIN `think_or_app_user` au ON osy.userid = au.id LEFT JOIN `think_or_guest` og ON osy.guestid = og.id WHERE osy.addtime >= ' + starttime + ' AND osy.addtime < ' + endtime + ' AND au.xiaozuid = ' + jsonshop + ' AND osy.huifangjilu = 0 AND osy.guestid <> 0 AND osy.guestid <> 1 ');
        } else {
          var info = await this.model().query('SELECT au.name as username,og.name as guestname,au.headurl,osy.huifangjilu,osy.addtime,au.sex,og.sex as gsex,osy.id FROM `think_or_shop_yejiticheng` osy LEFT JOIN `think_or_app_user` au ON osy.userid = au.id LEFT JOIN `think_or_guest` og ON osy.guestid = og.id WHERE osy.addtime >= ' + starttime + ' AND osy.addtime < ' + endtime + ' AND au.id = ' + user_id + ' AND osy.huifangjilu = 0 AND osy.guestid <> 0 AND osy.guestid <> 1  ');
        }
        break;
    }

    return think.isEmpty(info) ? this.json({ 'code': '200', 'msg': '查找失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': '查找成功...', 'data': info });
  }

  // 获取业绩提成信息下的订单信息
  async getosyinfoAction() {
    const yejiid = this.get('yejiid');
    const res = await this.model().query(' SELECT og.name,og.sex,og.headurl,og.phone,og.arrivetime,og.lv,od.name as shopname,osy.userid,au.name as username,au.headurl as userheadurl,au.sex as usex,og.id as guestid,osy.orderid FROM `think_or_shop_yejiticheng` osy LEFT JOIN `think_or_guest` og ON osy.guestid = og.id LEFT JOIN `think_or_department` od ON og.departmentid = od.id LEFT JOIN `think_or_app_user` au ON osy.userid = au.id WHERE osy.id = ' + yejiid + ' ');
    return think.isEmpty(res) ? this.json({ 'code': '200', 'msg': '查找失败...', 'data': '' }) : this.json({ 'code': '100', 'msg': '查找成功...', 'data': res });
  }
  // 获取并保存服务记录
  async postjiluhuifangAction() {
    const addinfo = this.post();
    const type = this.post('type');
    addinfo.addtime = Math.round(Date.now() / 1000);
    const osyid = this.post('osyid');
    const content = this.post('content');
    if (type == 1) {
      var res = this.model('or_shop_yejiticheng').where({ id: osyid }).update({ fuwujilu: 1 });
    } else {
      var res = this.model('or_shop_yejiticheng').where({ id: osyid }).update({ huifangjilu: 1 });
    }

    if (!think.isEmpty(content)) { const res1 = this.model('or_jilu_huifang').add(addinfo) }
    return think.isEmpty(res) ? this.json({ 'code': '200', 'msg': '操作失败！...', 'data': '' }) : this.json({ 'code': '100', 'msg': '操作成功！...', 'data': '' });
  }
  // 填写报表时的数据生成
  async getinfowritedaysheetAction() {
    const floor = this.get('floor');
    const jsonshop = this.get('jsonshop');
    const user_id = this.get('user_id');
    const ismanage = this.get('ismanage');

    const year = new Date().getFullYear(); // 获取年份
    const month = new Date().getMonth() + 1; // 获取月份
    const day = new Date().getDate(); // 获取日期
    // 获取今日开始的时间戳
    const starttime = Math.round(new Date(new Date().toDateString()).getTime() / 1000);
    // 今天结束时间
    const endtime = starttime + 86400;
    // 定义api获取地址
    const datapath = think.config('mypath');
    const getapi = this.controller(datapath + '/database');

    if (floor == 3 && ismanage == 0) { // 如果是普通员工
      const basenum = await getapi.getguestplannum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 规划客数
      const comenum = await getapi.getguestcomenum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 到店客数
      const bespeaknum = await getapi.getguestbesknum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 预约客户数量
      const bespeakarrive = await getapi.getguestbeskarrivenum(starttime, endtime, floor, jsonshop, ismanage, user_id);// 预约到店数量
      const planfeat = await getapi.getyejiplanxianjin(starttime, endtime, floor, jsonshop, ismanage, user_id);// 规划现金业绩
      const xianjin = await getapi.getyejixianjin(starttime, endtime, floor, jsonshop, ismanage, user_id);// 实际现金业绩
      const kahao = await getapi.getyejikahao(starttime, endtime, floor, jsonshop, ismanage, user_id);// 卡耗业绩

      return this.json({ 'data': { 'basenum': basenum, 'comenum': comenum, 'bespeaknum': bespeaknum, 'bespeakarrive': bespeakarrive, 'planfeat': planfeat, 'xianjin': xianjin, 'kahao': kahao } });
    } else { // 如果不是普通员工
      const myyeji_xianjin = await getapi.getyejiplanxianjin(starttime, endtime, 3, 0, 0, user_id);// 规划客数
      const myyeji_kahao = await getapi.getyejiplanxianjin(starttime, endtime, 3, 0, 0, user_id);// 规划客数
      return this.json({ 'data': { myyeji: myyeji } });
    }
  }
  // 查询是否已提交报表
  async getcheckusersheetAction() {
    const user_id = this.get('user_id');
    // 获取今日开始的时间戳
    const time_start_today = Math.round(new Date(new Date().toDateString()).getTime() / 1000);
    // 今天结束时间
    const time_end_today = time_start_today + 86400;

    const info = await this.model().query(' SELECT au.name,au.headurl,oud.addtime,oud.xiaoshou,oud.xiaohao,oud.bespeaknum,oud.xiaoshounum,oud.xiaohaonum,oud.jilunum,oud.huifannum,oud.workscore,oud.info,oud.daynum FROM `think_or_user_daysheet` oud LEFT JOIN `think_or_app_user` au ON oud.userid = au.id WHERE oud.addtime > ' + time_start_today + ' AND oud.addtime < ' + time_end_today + ' AND userid = ' + user_id + '  ');
    return think.isEmpty(info) ? this.json({ 'code': '200', 'msg': '没有数据...', 'data': '' }) : this.json({ 'code': '100', 'msg': '查询成功...', 'data': info });
  }

  // bottom
};
